<template>
  <div class="ivz-preview-search">
    <AForm layout="inline" :model="searchModel" ref="searchFormRef">
      <IvzSearchPreviewItem v-for="meta in searchMetas" :key="meta.id" :meta="meta" :edit-model="searchModel" />
      <AButton v-for="func in searchFunMetas" :key="func.func" class="ivz-ps-func" @click="() => clickHandle(func)">
        {{func.name}}
      </AButton>
    </AForm>
  </div>
</template>

<script>
import Preview from './index.js'
import {mapGetters, useStore} from "vuex";
import IvzSearchPreviewItem from "@/components/preview/IvzSearchPreviewItem.vue";
import {inject, reactive, ref, watch} from "vue";
export default {
  name: "IvzPreviewSearch",
  components: {IvzSearchPreviewItem},
  computed: {
    ...mapGetters(['searchMeta', 'searchMetas', 'searchFunMetas', 'preview'])
  },
  setup() {
    let store = useStore();
    let searchFormRef = ref(null);
    let searchModel = ref({});
    let preview = store.getters['preview']
    let context = inject(Preview.PreviewProvideContext);

    watch(() => preview.status, (newVal) => {
      if(newVal) {
        searchModel.value = {};
        store.getters['searchMetas'].forEach(item => {
          searchModel.value[item.id] = null;
        })
      }
    }, {deep: true})
    return {searchModel, searchFormRef, context}
  },
  mounted() {
    this.context.query(this.searchModel);
  },
  methods: {
    clickHandle(meta) {
      if(meta.func == 'reset') {
        this.searchFormRef.resetFields();
        this.context.query(this.searchModel);
      } else if(meta.func == 'query') {
        this.context.query(this.searchModel);
      } else if(meta.func == 'add') {
        this.context.add();
        this.preview.editVisible = true;
      }
    }
  }
}
</script>

<style scoped>
.ivz-ps-func {
  margin-left: 6px;
}

.ivz-preview-search {
  padding: 0px;
}
</style>